<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" :
 * <thepixeldeveloper@googlemail.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Mathew Davies
 * ----------------------------------------------------------------------------
 */
 
/**
* Redux Authentication 2
*/
class redux_auth
{
	/**
	 * CodeIgniter global
	 *
	 * @var string
	 **/
	protected $ci;

	/**
	 * account status ('not_activated', etc ...)
	 *
	 * @var string
	 **/
	protected $status;
	
	var $_captcha_image;

	/**
	 * __construct
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function __construct()
	{
		$this->ci =& get_instance();
		//$email = $this->ci->config->item('email');
		$this->ci->load->library('email');
		$this->ci->load->model("redux_auth/users_model", "redux_auth_model");
	}
	
	/**
	 * Activate user.
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function activate($identity)
	{
		return $this->ci->redux_auth_model->activate($identity);
	}
	
	/**
	 * Deactivate user.
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function deactivate($identity)
	{
	    return $this->ci->redux_auth_model->deactivate($identity);
	}
	
	/**
	 * Change password.
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function change_password($identity, $new)
	{
        return $this->ci->redux_auth_model->change_password($identity, $new);
	}

	/**
	 * forgotten password feature
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function forgotten_password($email)
	{
		$forgotten_password = $this->ci->redux_auth_model->forgotten_password($email);
		
		if ($forgotten_password)
		{
			// Get user information.
			$profile = $this->ci->redux_auth_model->profile($email);

			$data = array('identity'                => $profile->{$this->ci->config->item('identity')},
    			          'forgotten_password_code' => $this->ci->redux_auth_model->forgotten_password_code);
                
			$message = $this->ci->load->view($this->ci->config->item('email_templates').'forgotten_password', $data, true);
				
			$this->ci->email->clear();
			$this->ci->email->set_newline("\r\n");
			$this->ci->email->from('', '');
			$this->ci->email->to($profile->email);
			$this->ci->email->subject('Email Verification (Forgotten Password)');
			$this->ci->email->message($message);
			return $this->ci->email->send();
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * undocumented function
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function forgotten_password_complete($code)
	{
	    $identity                 = $this->ci->config->item('identity');
	    $profile                  = $this->ci->redux_auth_model->profile($code);
		$forgotten_password_complete = $this->ci->redux_auth_model->forgotten_password_complete($code);

		if ($forgotten_password_complete)
		{
			$data = array('identity'    => $profile->{$identity},
				         'new_password' => $this->ci->redux_auth_model->new_password);
            
			$message = $this->ci->load->view($this->ci->config->item('email_templates').'new_password', $data, true);
				
			$this->ci->email->clear();
			$this->ci->email->set_newline("\r\n");
			$this->ci->email->from('', '');
			$this->ci->email->to($profile->email);
			$this->ci->email->subject('New Password');
			$this->ci->email->message($message);
			return $this->ci->email->send();
		}
		else
		{
			return false;
		}
	}

	/**
	 * register
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function register($username, $password, $email, $additional_data = NULL)
	{
	    $email_activation = $this->ci->config->item('email_activation');
	    $email_folder     = $this->ci->config->item('email_templates');

		if (!$email_activation)
		{
			return $this->ci->redux_auth_model->register($username, $password, $email, $additional_data);
		}
		else
		{
			$register = $this->ci->redux_auth_model->register($username, $password, $email, $additional_data);
            
			if (!$register) { return false; }

			$deactivate = $this->ci->redux_auth_model->deactivate($username);

			if (!$deactivate) { return false; }

			$activation_code = $this->ci->redux_auth_model->activation_code;

			$data = array('username' => $username,
        				'password'   => $password,
        				'email'      => $email,
        				'activation' => $activation_code);
            
			$message = $this->ci->load->view($email_folder.'activation', $data, true);
            
			$this->ci->email->clear();
			$this->ci->email->set_newline("\r\n");
			$this->ci->email->from('smorete@gmail.com', 'Auth Sistem');
			$this->ci->email->to($email);
			$this->ci->email->subject('Email Activation (Registration)');
			$this->ci->email->message($message);
			
			return $this->ci->email->send();
		}
	}
	
	/**
	 * login
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function login($identity, $password)
	{
		$result = $this->ci->redux_auth_model->login($identity, $password);
		
		if($result !== FALSE){
        	//Limpiar logins attemps
        	// Clear login attempts
			$this->_clear_login_attempts();
        } else{
        	//aumentar login attemps
        	$this->_increase_login_attempt();
        }
		
		return $result;
	}
	
	/**
	 * logout
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function logout()
	{
	    $identity = $this->ci->config->item('identity');
	    $this->ci->session->unset_userdata($identity);
		$this->ci->session->sess_destroy();
	}
	
	/**
	 * logged_in
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function logged_in()
	{
	    $identity = $this->ci->config->item('identity');
		return ($this->ci->session->userdata($identity)) ? true : false;
	}
	
	/**
	 * Profile
	 *
	 * @return void
	 * @author Mathew
	 **/
	public function profile()
	{
	    $session  = $this->ci->config->item('identity');
	    $identity = $this->ci->session->userdata($session);
	    return $this->ci->redux_auth_model->profile($identity);
	}
	
	/** Añadidas SMORETE **/
	
	
	/**
	 * Change user info.
	 *
	 * @return void
	 * @author Sergio Morete Lopez
	 **/
	public function change_user_info($identity, $additional_data = NULL)
	{
        return $this->ci->redux_auth_model->change_user_info($identity, $additional_data);
	}
	
	// Increase login attempt
	function _increase_login_attempt()
	{		
		if ($this->ci->config->item('count_login_attempts') AND ! $this->is_max_login_attempts_exceeded())
		{
			// Load model
			$this->ci->load->model('dx_auth/login_attempts', 'login_attempts');		
			// Increase login attempts for current IP
			$this->ci->login_attempts->increase_attempt($this->ci->input->ip_address());
		}
	}

	// Clear login attempts
	function _clear_login_attempts()
	{
		if ($this->ci->config->item('count_login_attempts'))
		{
			// Load model
			$this->ci->load->model('redux_auth/login_attempts_model', 'login_attempts');		
			// Clear login attempts for current IP
			$this->ci->login_attempts->clear_attempts($this->ci->input->ip_address());
		}
	}
	
	// Check if login attempts bigger than max login attempts specified in config
	function is_max_login_attempts_exceeded()
	{
		$this->ci->load->model('redux_auth/login_attempts_model', 'login_attempts');
		
		return ($this->ci->login_attempts->check_attempts($this->ci->input->ip_address())->num_rows() >= $this->ci->config->item('max_login_attempts'));
	}
	
	/** Captcha functions **/
	function captcha()
	{
		$this->ci->load->helper('url');
	
		$this->ci->load->plugin('dx_captcha');
		
		$captcha_dir = trim($this->ci->config->item('captcha_path'), './');

		$vals = array(
			'img_path'	 	=> './'.$captcha_dir.'/',
			'img_url'		=> base_url().$captcha_dir.'/',
			'font_path'	 	=> $this->ci->config->item('captcha_fonts_path'),
			'font_size'  	=> $this->ci->config->item('captcha_font_size'),
			'img_width'	 	=> $this->ci->config->item('captcha_width'),
			'img_height' 	=> $this->ci->config->item('captcha_height'),
			'show_grid'	 	=> $this->ci->config->item('captcha_grid'),
			'expiration' 	=> $this->ci->config->item('captcha_expire')
		);
		
		$cap = create_captcha($vals);

		$store = array(
			'captcha_word' => $cap['word'],
			'captcha_time' => $cap['time']
		);

		// Plain, simple but effective
		$this->ci->session->set_flashdata($store);

		// Set our captcha
		$this->_captcha_image = $cap['image'];
	}
	
	function get_captcha_image()
	{
		return $this->_captcha_image;
	}
	
	// Check if captcha already expired
	// Use this in callback function in your form validation
	function is_captcha_expired()
	{
		// Captcha Expired
		list($usec, $sec) = explode(" ", microtime());
		$now = ((float)$usec + (float)$sec);	
		
		// Check if captcha already expired
		return (($this->ci->session->flashdata('captcha_time') + $this->ci->config->item('captcha_expire')) < $now);						
	}
	
	// Check is captcha match with code
	// Use this in callback function in your form validation
	function is_captcha_match($code)
	{
		if ($this->ci->config->item('captcha_case_sensitive'))
		{
			// Just check if code is the same value with flash data captcha_word which created in captcha() function		
			$result = ($code == $this->ci->session->flashdata('captcha_word'));
		}
		else
		{
			$result = strtolower($code) == strtolower($this->ci->session->flashdata('captcha_word'));
		}
		
		return $result;
	}		
	
	/* End of captcha related function */
	
}
